package cn.yunwei.module.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author wangbinggui
 */
@Component
public class RequestHeaderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 校验 X-Custom-Header
        String customHeader = request.getHeader("X-Custom-Header");
        if (customHeader == null || customHeader.isEmpty()) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing required header: X-Custom-Header");
            return false;
        }

        // 校验 Authorization
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || authHeader.isEmpty()) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing required header: Authorization");
            return false;
        }

        // 如果 Authorization 采用 Bearer Token 认证，进一步检查格式
        if (!authHeader.startsWith("Bearer ")) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Authorization format");
            return false;
        }

        return true;
    }
}